<template>
	<view class="video-device-form">
		<!-- <view class="header">
			<img src="../../static/arrow.png" alt="" class="back-img" />
			<text class="header-title">视频调试</text>
		</view> -->
		<!-- 边设备信息 -->
		<view class="video-device-container">
			<view class="form-header">
				<view class="flex-alin">
					<text class="header-text">NVR信息</text>
					<view class="header-tag">
						<uni-tag text="在线" type="success"></uni-tag>
					</view>
				</view>

				<view class="header-button">
					<button type="primary" class="header-btn" @click="initNVR()">
						<view class="icon-container">
							<image src="../../static/circule.png" mode="" class="icon"></image>
						</view>初始化NVR
					</button>
				</view>
			</view>

			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog title="新增摄像机" :before-close="true" @close="close()" @confirm="addCamera()">
					<uni-forms ref="deviceForm" :rules="rules" :modelValue="formData" class="form-container-box">
						<uni-forms-item label="ip" required name="ip" class="info-item">
							<uni-easyinput :clearable="false" v-model="formData.ip" placeholder="请输入IP" />
						</uni-forms-item>
						<uni-forms-item label="端口" required name="port" class="info-item">
							<uni-easyinput :clearable="false" v-model="formData.port" placeholder="请输入端口" />
						</uni-forms-item>
						<uni-forms-item label="用户名" required name="user" class="info-item">
							<uni-easyinput :clearable="false" v-model="formData.user" placeholder="请输入用户名" />
						</uni-forms-item>
						<uni-forms-item label="密码" required name="password" class="info-item">
							<uni-easyinput :clearable="false" v-model="formData.password" placeholder="请输入密码" />
						</uni-forms-item>
					</uni-forms>
				</uni-popup-dialog>
			</uni-popup>

			<uni-popup style="width: 600px;" ref="networkDialog" type="dialog">
				<uni-popup-dialog style="width: 600px;" title="网络设置" :before-close="true" @close="closeNetwork()"
					@confirm="handleNetworkConfig()">
					<!-- :rules="rules"  -->

					<uni-forms style="width: 550px;" ref="configForm" :modelValue="networkForm"
						class="form-container-box">
						<uni-forms-item label-width="80px" label="序列号" required name="serial" class="info-item">
							<uni-easyinput disabled :clearable="false" v-model="networkForm.serial"
								placeholder="请输入序列号" />
						</uni-forms-item>
						<uni-forms-item label-width="80px" label="密码" required name="pass" class="info-item">
							<uni-easyinput :clearable="false" v-model="networkForm.pass" placeholder="请输入密码" />
						</uni-forms-item>
						<uni-forms-item label-width="80px" label="IP" required name="ip" class="info-item">
							<uni-easyinput :clearable="false" v-model="networkForm.ip" placeholder="请输入ip" />
						</uni-forms-item>
						<uni-forms-item label-width="80px" label="端口" required name="port" class="info-item">
							<uni-easyinput :clearable="false" v-model="networkForm.port" placeholder="请输入端口" />
						</uni-forms-item>
						<uni-forms-item label-width="80px" label="网络掩码" required name="mask" class="info-item">
							<uni-easyinput :clearable="false" v-model="networkForm.mask" placeholder="请输入掩码" />
						</uni-forms-item>
						<uni-forms-item label-width="80px" label="网关" required name="gateway" class="info-item">
							<uni-easyinput :clearable="false" v-model="networkForm.gateway" placeholder="请输入网关地址" />
						</uni-forms-item>

						<!-- <uni-section title="单行显示" subTitle="使用 single 属性单行显示通知" type="line"> -->
						<uni-notice-bar single text="请确认密码配置是否正确，短时间内频繁修改IP地址将会导致摄像机被锁死30分钟" />
						<!-- </uni-section> -->
					</uni-forms>


				</uni-popup-dialog>
			</uni-popup>



			<view class="video-device-info">
				<view class="form-row">
					<!-- 设备名称 -->
					<uni-forms-item label="设备名称" required name="name" class="info-item" label-width=60>
						<uni-easyinput disabled v-model="nvr.name" placeholder="请输入设备名称" />
					</uni-forms-item>

					<uni-forms-item label="IP" required name="ip" class="info-item" label-width=60>
						<uni-easyinput disabled v-model="nvr.ip" placeholder="请输入IP" />
					</uni-forms-item>
				</view>

				<view class="form-row-last">
					<!-- 可用硬盘容量 -->
					<uni-forms-item label="可用硬盘容量" name="freeSpace" class="info-item" label-width=60>
						<uni-easyinput disabled v-model="disk.freeSpace" placeholder="正在初始化" />
					</uni-forms-item>


				</view>

			</view>
		</view>

		<!-- 视频设备列表 -->
		<view class="video-device-list-container">
			<view class="video-device-list-header">
				<text class="video-device-list-title">视频设备列表</text>
				<view class="video-device-list-buttons">


					<button type="primary" class="discover-btn" @click="clickFind()">
						<view class="icon-container">
							<image src="../../static/compass.png" mode="" class="icon"></image>
						</view>设备发现
					</button>
					<button type="primary" class="add-camera-btn" @click="gotoAddCamera()">
						<view class="icon-container">
							<image src="../../static/lu_03.png" mode="" class="icon"></image>
						</view>添加摄像机
					</button>
				</view>
			</view>

			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th width="70" align="center">通道号</uni-th>
					<uni-th width="100" align="center">通道名称</uni-th>
					<uni-th width="80" align="center">设备类型</uni-th>
					<uni-th width="100" align="center">IP地址</uni-th>
					<uni-th width="100" align="center">状态</uni-th>

					<uni-th width="150" align="center">操作</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in cameraTable" :key="index">
					<uni-td align="center">{{ item.channel }}</uni-td>
					<uni-td align="center">{{ item.name }}</uni-td>
					<uni-td align="center">
						<view v-if="item.type==='box'">枪机</view>
						<view v-if="item.type==='dome'">球机</view>
					</uni-td>
					<uni-td align="center">{{ item.ip }}</uni-td>
					<uni-td align="center">
						<uni-tag v-if=" item.state=== 1" text="在线" type="success"></uni-tag>
						<uni-tag v-if=" item.state=== 2" text="离线" type="default"></uni-tag>
						<uni-tag v-if=" item.state=== 3" text="未分配" type="warning"></uni-tag>
						<uni-tag v-if=" item.state=== 4" text="未激活" type="error"></uni-tag>
					</uni-td>
					<uni-td align="center">
						<button v-if="item.channel" size="mini" type="default" @click="videoPreview(item)">查看</button>
						<button v-if="item.channel" size="mini" type="error" @click="deleteFromTable(item)">删除</button>
						<button v-if="item.state === 4" size="mini" type="error"
							@click="activateCamera(item)">激活</button>
						<button v-if="item.state === 3||item.state === 4" size="mini" type="error"
							@click="editCameraConfig(item)">编辑</button>
						<!-- <button size="mini" type="default" @click="videoPreview(item)">查看</button> -->
					</uni-td>
				</uni-tr>

			</uni-table>

		</view>


		<!-- 底部 -->
		<view class="button-bar">
			<button type="primary" class="add-channel-btn" @click="allocateChannel()">
				<view class="icon-container">
					<image src="../../static/check.png" mode="" class="icon"></image>
				</view>分配通道
			</button>
			<!-- <button type="primary" class="import-btn">导入平台台账</button> -->
			<button type="primary" class="save-btn-video" @click="saveVideo()">
				<view class="icon-container">
					<image src="../../static/check.png" mode="" class="icon"></image>
				</view>保存设置
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, reactive, nextTick } from 'vue'
	import { WEB_URL } from '../../config/global';
	import { getJsonData } from '../../js_sdk/file';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const videoDeviceList = ref()
	const deviceFind = ref()
	const inputDialog = ref()
	const station = ref()
	const configForm = ref()
	const table = ref()
	const statusCode = ref()
	const platformData = ref()
	const defaultInfo = ref()
	const waitChannelList = ref([])
	const cameraTable = ref([])
	const activated = ref()
	const deviceForm = ref();
	const networkDialog = ref();
	const serial = ref()
	const loading = ref(true)
	const disk = ref({
		freeSpace: '无硬盘数据'
	})
	const nvr = ref({

	})
	const formData = reactive({
		password: "",
		user: "",
		ip: "",
		port: "",
		manual: "1"
	})

	const networkForm = ref({
		serial: "",
		pass: "",
		ip: "",
		port: "",
		mask: "",
		gateway: ""
	})
	const selectedIndexs = ref([]);

	//设备发现中的camera
	const cameraFromFind = ref([]);
	//通道信息中的camera
	const cameraFromChannel = ref([]);
	//设备列表中的camera
	const cameraFromDeivce = ref([]);

	const rules = {
		ip: {
			rules: [{
				required: true,
				errorMessage: 'ip不能为空'
			}, {
				validateFunction: function (rule, value, data, callback) {
					let reg = /^((2((5[0-5])|([0-4]\d)))|([0-1]?\d{1,2}))(\.((2((5[0-5])|([0-4]\d)))|([0-1]?\d{1,2}))){3}$/
					if (reg.test(value)) {
						return true
					} else {
						callback('ip地址格式错误')
					}
				}
			}]
		},
		port: {
			rules: [{
				required: true,
				errorMessage: '端口不能为空'
			}, {
				validateFunction: function (rule, value, data, callback) {
					let reg = /^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/
					if (reg.test(value)) {
						return true
					} else {
						callback('端口格式错误')
					}
				}
			}]
		},
		user: {
			rules: [{
				required: true,
				errorMessage: '用户名不能为空'
			}]
		},
		password: {
			rules: [{
				required: true,
				errorMessage: '密码不能为空'
			}]
		}
	};

	onLoad(async (options) => {
		if (!Object.keys(options).length == 0) {
			station.value = JSON.parse(decodeURIComponent(options.item))
			console.log('station.value', station.value);
		}

		let filePath2 = '_doc/test/platform.json'
		let dataJson2 = await getJsonData(filePath2)
		if (dataJson2 === '') {
		} else {
			platformData.value = JSON.parse(dataJson2);
		}

		// station.value = {
		// 	videoData: {
		// 		videoPort: 8000,
		// 		videoUsername: "admin",
		// 		videoPassword: "njzt12345"
		// 	},
		// 	gatewayData: {
		// 		gatewayIP: "192.168.1.155",
		// 		gatewayPort: 8000,
		// 		gatewayPassword: 'njzt12345'
		// 	}
		// }
		// nvr.value.ip = "192.168.1.155"
		uni.showLoading({
			title: '数据加载中'
		});

		formData.port = station.value.videoData.videoPort
		formData.password = station.value.videoData.videoPassword
		formData.user = station.value.videoData.videoUsername

		//1.获取设备列表 
		// await getDeviceList()
		//2.默认调用一次设备发现
		await find()
		//3.查询硬盘
		const res = await getDiskData()

		if (res === '400') {
			uni.showModal({
				title: '提示',
				content: '硬盘异常，数据初始化失败，请检查。',
				confirmText: "确定",
				showCancel: false,
			})
		} else {
			//4.初始化通道信息
			await getChannelInfo()
			initTableData()
		}

	})

	const activateCamera = (camera) => {
		let params = {
			driver: "hiknet",
			serial: camera.serial,
			pass: station.value.videoData.videoPassword
		}

		uni.request({
			url: WEB_URL + '/find?t=activate',
			data: params,
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			},
			dataType: 'json',
			success: async (res) => {
				uni.showToast({
					title: "激活成功",
					icon: "success"
				})

				await find()
				//3.查询硬盘
				const res2 = await getDiskData()

				if (res2 === '400') {
					uni.showModal({
						title: '提示',
						content: '硬盘异常，数据初始化失败，请检查。',
						confirmText: "确定",
						showCancel: false,
					})
				} else {
					//4.初始化通道信息
					await getChannelInfo()
					initTableData()
				}
			},
			fail(err) {
				console.log(err)

			}
		})

	}

	const editCameraConfig = (camera) => {
		networkForm.value.serial = camera.serial
		networkForm.value.pass = station.value.videoData.videoPassword
		networkForm.value.port = station.value.videoData.videoPort
		networkForm.value.ip = camera.ip
		networkForm.value.mask = camera.mask
		networkForm.value.gateway = camera.gateway
		networkDialog.value.open()
	}


	/**
	 * 三个cameraList做匹配 并渲染表格
	 */
	const initTableData = async () => {
		console.log('cameraFromFind.value', cameraFromFind.value);
		console.log('cameraTable.value', cameraTable.value);
		console.log('cameraFromChannel.value', cameraFromChannel.value);
		cameraTable.value = []

		//设备发现的摄像机直接加入表格
		for (let j = 0; j < cameraFromFind.value.length; j++) {
			if (cameraFromFind.value[j].majorType === 1) {
				let obj = {}
				obj.ip = cameraFromFind.value[j].ip
				obj.mask = cameraFromFind.value[j].mask
				obj.gateway = cameraFromFind.value[j].gateway
				obj.serial = cameraFromFind.value[j].serial
				obj.port = cameraFromFind.value[j].port
				obj.state = cameraFromFind.value[j].activated === 1 ? 3 : 4
				cameraTable.value.push(obj)
			}
		}

		for (let i = 0; i < cameraFromChannel.value.length; i++) {
			let find = cameraTable.value.find(function (item) {
				return item.ip === cameraFromChannel.value[i].ip;
			});

			//不在设备发现列表中的设备
			if (find === undefined || find === null) {
				let obj = {}
				obj.ip = cameraFromChannel.value[i].ip
				obj.port = cameraFromChannel.value[i].port
				obj.channel = cameraFromChannel.value[i].channel
				obj.user = cameraFromChannel.value[i].user
				obj.pass = cameraFromChannel.value[i].pass
				obj.type = cameraFromChannel.value[i].type
				obj.state = cameraFromChannel.value[i].state
				obj.name = cameraFromChannel.value[i].name
				obj.rtspUrl = cameraFromChannel.value[i].rtspUrl
				cameraTable.value.push(obj)
			} else {
				find.channel = cameraFromChannel.value[i].channel
				find.user = cameraFromChannel.value[i].user
				find.pass = cameraFromChannel.value[i].pass
				find.type = cameraFromChannel.value[i].type
				find.name = cameraFromChannel.value[i].name
				find.state = cameraFromChannel.value[i].state
				find.rtspUrl = cameraFromChannel.value[i].rtspUrl
			}
		}
		cameraTable.value.sort(function (a, b) {
			return a.state - b.state
		})

		cameraTable.value.sort(function (a, b) {
			return a.channel - b.channel
		})

		loading.value = false



	}

	/**
	 * 获取通道信息
	 */
	const getChannelInfo = () => {
		cameraFromChannel.value = []
		let params = {
			driver: "hiknet",
			ip: nvr.value.ip,
			port: station.value.videoData.videoPort,
			user: station.value.videoData.videoUsername,
			pass: station.value.videoData.videoPassword
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: WEB_URL + '/nvr?t=info',
				data: params,
				method: 'POST',
				header: {
					'Content-Type': 'application/json'
				},
				dataType: 'json',
				success: (res) => {
					cameraFromChannel.value = res.data
					console.log(res.data);
					resolve('suc');
				},
				fail(err) {
					console.log(err)
					reject('err')
				}
			})
		})
	}

	/**
	 * 获取设备列表
	 */
	const getDeviceList = () => {
		return new Promise((resolve, reject) => {
			uni.request({
				url: WEB_URL + '/app/getVideoDevice',
				method: 'GET',
				timeout: 5000,
				success: (res) => {
					//取第一个NVR设备
					if (res.data.data.length > 0) {
						nvr.value = res.data.data[0]
						//获取cameras
						if (nvr.value.cameras.length > 0) {
							cameraFromDeivce.value = nvr.value.cameras
						}
					}
					resolve('suc');
				},
				fail(err) {
					uni.showModal({
						title: '提示',
						content: '获取设备列表失败，系统异常',
						confirmText: "确定",
						showCancel: false,
					})
					reject('err')
				}
			})
		})
	}

	/**
	 * 保存配置
	 */
	const saveVideo = async () => {
		uni.showModal({
			title: '提示',
			content: '是否确认保存配置?',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success: (res) => {
				if (res.confirm) {
					if (selectedIndexs.value.length < 1) {
						uni.showToast({
							title: '请至少选择一个摄像机',
							icon: 'none'
						});
						return
					}
					let cameras = []
					for (let i = 0; i < cameraTable.value.length; i++) {
						if (cameraTable.value[i].channel != undefined || cameraTable.value[i].channel != null) {
							let obj = {}
							obj.name = cameraTable.value[i].name
							obj.type = cameraTable.value[i].type
							obj.channel = cameraTable.value[i].channel
							obj.sgcode = cameraTable.value[i].sgcode
							cameras.push(obj)
						}
					}
					let data = []
					data.push({
						name: nvr.value.name,
						ip: nvr.value.ip,
						port: nvr.value.port,
						username: nvr.value.username,
						password: nvr.value.password,
						drivertype: "5",
						cameras: cameras
					})
					let params = {
						data: data
					}
					uni.request({
						url: WEB_URL + '/app/addVideoDevice',
						data: params,
						method: 'POST',
						header: {
							'Content-Type': 'application/json'
						},
						dataType: 'json',
						success: async (res) => {
							if (res.data.code === 0) {
								uni.showToast({
									title: "保存成功",
									icon: "success"
								})
								// uni.navigateTo({
								// 	url: '/pages/videoConfigure/videoConfigure'
								// })
								await find()
								//3.查询硬盘
								const res = await getDiskData()

								if (res === '400') {
									uni.showModal({
										title: '提示',
										content: '硬盘异常，数据初始化失败，请检查。',
										confirmText: "确定",
										showCancel: false,
									})
								} else {
									//4.初始化通道信息
									await getChannelInfo()
									initTableData()
								}
							} else {
								uni.showModal({
									title: '提示',
									content: res.data.message,
									confirmText: "确定",
									showCancel: false,
								})
							}
						},
						fail: (err) => {
							uni.showModal({
								title: '提示',
								content: '保存失败，系统异常',
								confirmText: "确定",
								showCancel: false,
							})
						},
					})
				} else {
				}
			}
		})

	}

	/**
	 * 硬盘数据
	 */
	const getDiskData = () => {
		let params = {
			driver: "hiknet",
			ip: nvr.value.ip,
			port: station.value.videoData.videoPort,
			user: station.value.videoData.videoUsername,
			pass: station.value.videoData.videoPassword
		}
		//查询硬盘数据
		return new Promise((resolve, reject) => {
			uni.request({
				url: WEB_URL + '/nvr?t=getdisk',
				data: params,
				method: 'POST',
				header: {
					'Content-Type': 'application/json'
				},
				dataType: 'json',
				success: (res) => {
					disk.value = res.data[0]
					if (disk.value != undefined) {

						disk.value.freeSpace = (disk.value.freeSpace / 1024 / 1024).toFixed(1).toString() + "GB"

						uni.showToast({
							title: '硬盘已初始化',
							icon: 'success'
						});
					} else {
						disk.value.freeSpace = '无硬盘数据'
						uni.showToast({
							title: '硬盘已初始化',
							icon: 'success'
						});
					}
					resolve('0');
				},
				complete: (complete) => {
					//statusCode:400 不往下走
					if (complete.statusCode == 400) {
						uni.hideLoading()
						resolve('400');
					}
				},
				fail(err) {
					uni.showModal({
						title: '提示',
						content: '硬盘数据读取失败，系统异常',
						confirmText: "确定",
						showCancel: false,
					})
					reject('err')
				}
			})
		})
	}

	/**
	 * 设备发现
	 */
	const find = () => {
		uni.showLoading({
			title: '数据加载中'
		});
		cameraFromFind.value = []
		return new Promise((resolve, reject) => {
			uni.request({
				url: WEB_URL + '/find?t=find&wait=3&reset=1',
				method: 'GET',
				success: (res) => {
					console.log('find success');
					//返回一个数组
					if (res.data.length > 1) {
						//找到第一个NVR
						for (let i = 0; i < res.data.length; i++) {
							let flag = false
							if (res.data[i].majorType == 0) {
								if (flag == true) {
									continue
								}
								nvr.value = res.data[i]
								if (nvr.value.ip === res.data[i].ip) {
									serial.value = res.data[i].serial
								}
								flag = true
							}
							//摄像机设备
							if (res.data[i].majorType == 1) {
								cameraFromFind.value.push(res.data[i])
							}
						}
					}
					resolve('suc');
				},
				fail(err) {
					uni.showModal({
						title: '提示',
						content: '设备发现失败，系统异常',
						confirmText: "确定",
						showCancel: false,
					})
					reject('err')
				}
			})
		})

	}



	/**
	 * 初始化NVR：激活NVR 初始化硬盘
	 */
	const initNVR = async () => {
		// 用来测试
		// networkDialog.value.open()
		// //未激活则激活并格式化硬盘
		if (activated.value != 1) {
			let params = {
				driver: "hiknet",
				serial: serial.value,
				pass: station.value.videoData.videoPassword
			}
			uni.request({
				url: WEB_URL + '/find?t=activate',
				data: params,
				method: 'POST',
				header: {
					'Content-Type': 'application/json'
				},
				dataType: 'json',
				success: (res) => {
					uni.showToast({
						title: '激活成功',
						icon: 'success'
					})
				},
				fail(err) {
					uni.showModal({
						title: '提示',
						content: '激活失败，系统异常',
						confirmText: "确定",
						showCancel: false,
					})
					return
				}
			})
		} else {
			uni.showModal({
				title: '提示',
				content: '请勿重复激活',
				confirmText: "确定",
				showCancel: false,
			})
			return
		}

		let params2 = {
			driver: "hiknet",
			ip: nvr.value.ip,
			port: station.value.videoData.videoPort,
			user: station.value.videoData.videoUsername,
			pass: station.value.videoData.videoPassword,
			diskNumber: 1
		}
		uni.request({
			url: WEB_URL + '/nvr?t=formatdisk',
			data: params2,
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			},
			dataType: 'json',
			success: (res) => {
				uni.showToast({
					title: '硬盘已初始化',
					icon: 'success'
				});
				uni.redirectTo({
					url: `/pages/videoConfigure/videoConfigure?item=${encodeURIComponent(JSON.stringify(station.value))}`
				});
			},
			fail(err) {
				uni.showModal({
					title: '提示',
					content: '格式化硬盘失败，系统异常',
					confirmText: "确定",
					showCancel: false,
				})
			}
		})

	}

	/**
	 * 分配通道
	 */
	const allocateChannel = async () => {
		uni.showModal({
			title: '提示',
			content: '是否确认分配通道?',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success: async (res) => {
				if (res.confirm) {
					let info = []
					let flag = false
					console.log('1', selectedIndexs.value);
					if (selectedIndexs.value.length < 1) {
						uni.showToast({
							title: '请至少选择一个摄像机',
							icon: 'none'
						});
						return
					}


					//将选中的摄像机添加到参数中
					for (let i = 0; i < selectedIndexs.value.length; i++) {
						let param = {
							ip: cameraTable.value[selectedIndexs.value[i]].ip,
							port: cameraTable.value[selectedIndexs.value[i]].port,
							user: cameraTable.value[selectedIndexs.value[i]].user,
							pass: cameraTable.value[selectedIndexs.value[i]].password,
							srcChannel: 1
						}
						info.push(param)
					}


					let params = {
						driver: "hiknet",
						ip: nvr.value.ip,
						port: station.value.videoData.videoPort,
						user: station.value.videoData.videoUsername,
						pass: station.value.videoData.videoPassword,
						info: info
					}

					uni.request({
						url: WEB_URL + '/nvr?t=setinfo',
						data: params,
						method: 'POST',
						header: {
							'Content-Type': 'application/json'
						},
						dataType: 'json',
						success: async (res) => {
							uni.showToast({
								title: '设置通道信息成功',
								icon: 'success',
								duration: 1000
							});
							setTimeout(async function () {
								await find()
								//3.查询硬盘
								const res2 = await getDiskData()

								if (res2 === '400') {
									uni.showModal({
										title: '提示',
										content: '硬盘异常，数据初始化失败，请检查。',
										confirmText: "确定",
										showCancel: false,
									})
								} else {
									//4.初始化通道信息
									await getChannelInfo()
									initTableData()
								}
							}, 1500)

						},
						fail(err) {
							uni.showModal({
								title: '提示',
								content: '分配通道失败，系统异常',
								confirmText: "确定",
								showCancel: false,
							})
						}
					})

				}
			}
		})
	}

	const videoPreview = (camera) => {
		let options = {}
		camera.nvrIp = nvr.value.ip
		camera.nvrPort = nvr.value.port
		camera.pageName = 'videoConfigure'
		let other = cameraTable.value.filter((item) => {
			return item.hasOwnProperty('channel') && item.channel !== camera.channel
		})
		camera.other = other
		// options = encodeURIComponent(JSON.stringify(Object.assign(station.value, camera)))


		var cache = [];
		var json_str = JSON.stringify(Object.assign(station.value, camera), function (key, value) {
			if (typeof value === 'object' && value !== null) {
				if (cache.indexOf(value) !== -1) {
					return;
				}
				cache.push(value);
			}
			return value;
		});
		cache = null;	//释放cache

		uni.navigateTo({
			url: `/pages/videoPreview/videoPreview?item=${json_str}`,
		})
	}

	// 多选
	const selectionChange = (e) => {
		selectedIndexs.value = e.detail.index
	}

	/**
	 * 点击设备发现
	 */
	const clickFind = async () => {
		await find()
		//3.查询硬盘
		const res = await getDiskData()
		if (res === '400') {
			uni.showModal({
				title: '提示',
				content: '硬盘异常，数据初始化失败，请检查。',
				confirmText: "确定",
				showCancel: false,
			})
		} else {
			//4.初始化通道信息
			await getChannelInfo()
			initTableData()
		}
	}


	const addCamera = async () => {
		const valid = await deviceForm.value.validate();
		if (valid) {
			//json序列化深拷贝
			let data = JSON.parse(JSON.stringify(formData));
			cameraTable.value.push(data)
			uni.showToast({
				title: '添加成功',
				icon: 'success'
			});
			inputDialog.value.close()
			formData.ip = ""
			formData.password = ""
			formData.user = ""
			formData.port = ""
		} else {
			//校验失败
		}
	}

	/**
	 * 修改设备设置网络
	 */
	const handleNetworkConfig = () => {
		uni.showLoading({
			title: '正在修改设置网络'
		});
		let params = {
			driver: "hiknet",
			serial: networkForm.value.serial,
			pass: networkForm.value.pass,
			ip: networkForm.value.ip,
			port: networkForm.value.port,
			gateway: networkForm.value.gateway,
			mask: networkForm.value.mask
		}
		uni.request({
			url: WEB_URL + '/find?t=network',
			data: params,
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			},
			dataType: 'json',
			success: async (res) => {
				console.log(res);
				uni.showToast({
					title: '设备设置网络成功',
					icon: 'success',
					duration: 1500
				});
				networkForm.value.serial = ""
				networkForm.value.pass = ""
				networkForm.value.port = ""
				networkForm.value.ip = ""
				networkForm.value.mask = ""
				networkForm.value.gateway = ""
				networkDialog.value.close()

				//1.获取设备列表
				await getDeviceList()
				//2.默认调用一次设备发现
				await find()
				//3.查询硬盘
				await getDiskData()
				//4.初始化通道信息
				await getChannelInfo()
				initTableData()

			},
			fail(err) {
				uni.showModal({
					title: '提示',
					content: '分配通道失败，系统异常',
					confirmText: "确定",
					showCancel: false,
				})
			}
		})
	}


	const closeNetwork = () => {
		networkDialog.value.close()
	}

	const close = () => {
		formData.ip = ""
		formData.password = ""
		formData.user = ""
		formData.port = ""
		inputDialog.value.close()
	}


	const gotoAddCamera = () => {
		inputDialog.value.open()
	}

	const deleteFromTable = (camera) => {
		uni.showModal({
			title: '提示',
			content: '是否确认删除该摄像机?',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success: async (res) => {
				if (res.confirm) {
					let array = cameraFromChannel.value.filter(item => item.ip !== camera.ip)
					let info = []
					if (array.length > 0) {
						for (let i = 0; i < array.length; i++) {
							let param = {
								ip: array[i].ip,
								port: array[i].port,
								user: array[i].user,
								pass: array[i].pass,
								srcChannel: 1
							}
							info.push(param)
						}
					}
					let flag = false
					let params = {
						driver: "hiknet",
						ip: nvr.value.ip,
						port: station.value.videoData.videoPort,
						user: station.value.videoData.videoUsername,
						pass: station.value.videoData.videoPassword,
						info: info
					}
					uni.request({
						url: WEB_URL + '/nvr?t=setinfo',
						data: params,
						method: 'POST',
						header: {
							'Content-Type': 'application/json'
						},
						dataType: 'json',
						success: async (res) => {
							uni.showToast({
								title: '删除成功',
								icon: 'success',
								duration: 1000
							});

							//1.获取设备列表
							await getDeviceList()
							//2.默认调用一次设备发现
							await find()
							//3.查询硬盘
							await getDiskData()
							//4.初始化通道信息
							await getChannelInfo()
							initTableData()

						},
						fail(err) {
							uni.showModal({
								title: '提示',
								content: '删除失败，系统异常',
								confirmText: "确定",
								showCancel: false,
							})
						}
					})
				}
			},
		})


		// //1.获取设备列表
		// await getDeviceList()
		// //2.默认调用一次设备发现
		// await find()
		// //3.查询硬盘
		// await getDiskData()
		// //4.初始化通道信息
		// await getChannelInfo()
		// initTableData()

	}
</script>

<style>
	.flex-alin {
		display: flex;
		align-items: center;
	}

	/* 基本样式 */
	.video-device-form {
		padding: 45px 20px;
		background-color: #f7f7f7;
		/* border-radius: 8px; */
		height: 92vh;

	}

	.header {
		/* border: 1px solid red; */
		display: flex;
		justify-content: center;
		align-items: center;
		padding-bottom: 20px;
		position: relative;
	}

	.back-img {
		position: absolute;
		left: 0;
	}

	.header-title {
		font-size: 24px;
		color: #666;
	}

	.video-device-container {
		/* border: 1px solid red; */
		padding: 20px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		border-radius: 5px;
	}

	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.header-text {
		font-size: 24px;
		color: #666;
	}

	.header-tag {
		margin-left: 20px;
	}

	.header-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 16px;
		background-color: #48b0b1 !important;
		/* color: white; */
		padding: 0 20px;
		border-radius: 4px;
	}

	.icon-container {
		width: 20px;
		height: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10px;
	}

	.icon {
		width: 100%;
		height: 100%;
	}

	.video-device-info {
		width: 100%;
		margin-top: 20px;
	}

	.form-row {
		/* margin-top: 20px; */
		display: flex;
		justify-content: space-between;
		/* margin: 10px 0; */
	}

	.form-row-last {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
	}

	.info-item {
		flex: 1;
		margin-right: 10px;
		/* 为每个表单项添加右边距 */
	}



	/* 当前行只有最后一个输入框时，让它占一半 */
	.video-device-info>.last-item:last-child {
		flex: 1 1 calc(50% - 20px);
	}

	.label {
		font-size: 18px;
		color: #666;
		width: 120px;
		text-align: right;
		flex-shrink: 0;
		padding-right: 10px;
	}

	.input {
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 18px;

	}

	.video-device-list-container {
		margin-top: 20px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		border-radius: 8px;
		padding: 20px;
	}

	.video-device-list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.video-device-list-title {
		font-size: 24px;
		color: #666;
	}

	.video-device-list-buttons {
		display: flex;
		gap: 10px;
	}

	.add-channel-btn,
	.add-camera-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 4px;
		font-size: 16px;
	}

	.add-channel-btn {
		background-color: #48b0b1 !important;
	}

	.add-camera-btn {
		background-color: #07c160 !important;
	}

	.button-bar {
		/* position: fixed;
		bottom: 0;
		left: 0;
		right: 0; */

		display: flex;
		border-radius: 4px;
		font-size: 16px;
		padding: 20px;
		z-index: 1000;
	}

	.discover-btn {
		font-size: 16px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #5a79ff !important;
	}

	.import-btn {
		background-color: #48b0b1 !important;
	}

	.save-btn-video {
		font-size: 16px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #07c160 !important;
	}
</style>